﻿#include "mvbdevicedata.h"

#include <QByteArray>
#include <QDataStream>

mvbDeviceData::mvbDeviceData()
{
    data = nullptr;
}

mvbDeviceData::~mvbDeviceData()
{
    destroyData();
}

void mvbDeviceData::initdata()
{
    data = new unsigned char[m_size]{0};
    shortData = new unsigned short[m_size/2]{0};
}

void mvbDeviceData::destroyData()
{
    if(data!=nullptr)
    {
        delete []data;
        data=nullptr;
    }
}

QByteArray mvbDeviceData::serialize() const
{
    QByteArray byteArray;
    QDataStream stream(&byteArray, QIODevice::WriteOnly);

    // 写入基本类型
    stream << m_portType << m_size << m_circleTime << m_portAddress;

    // 写入data数组
     unsigned int shortSize = m_size/2;
    if (data != nullptr) {
        for (unsigned int i = 0; i < shortSize; ++i) {
            stream << shortData[i];
        }
    }

    return byteArray;
}

void mvbDeviceData::deserialize(const QByteArray &byteArray)
{
    QDataStream stream(byteArray);
    stream >> m_portType >> m_size >> m_circleTime >> m_portAddress;

    // 初始化data数组
    initdata();

    // 读取data数组
    unsigned int shortSize = m_size/2;
    for (unsigned int i = 0; i < shortSize; ++i) {
        stream >> shortData[i];
    }
}
